//
//  UIImage+AsynDraw.swift
//  WymanWeibo
//
//  Created by wyman on 16/4/18.
//  Copyright © 2016年 wyman. All rights reserved.
//

import UIKit

 extension UIImage {

    //异步绘制图片
    
    func hm_AsyncDrawImage(var size: CGSize?, bkgColor: UIColor? = UIColor.whiteColor(), isCorner: Bool = false, drawFinish: (image: UIImage)-> ()){
    
    dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
        let start = CACurrentMediaTime()
        
        if size == nil{
        
        size = self.size
            
        }
        
        let rect = CGRect(origin: CGPointZero, size: size!)
        
        //开启上下文
        
        UIGraphicsBeginImageContextWithOptions(size!, bkgColor != nil, UIScreen.mainScreen().scale)
        
        //设置背景颜色
        bkgColor?.setFill()
        UIRectFill(rect)
        
        if isCorner{
        
            let path = UIBezierPath(ovalInRect: rect)
            
            path.addClip()
        
        }
        
        self.drawInRect(rect)
        
        //获取图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        
        //结束上下文
        UIGraphicsEndImageContext()
        
        let end = CACurrentMediaTime()
        //返回绘制好的图片
        //异步绘制的时间
//        HMPrint("异步绘制时间:\(end - start)")
        
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            drawFinish(image: newImage)
        })
        
        }
    
    
    
    }




}